const express = require('express');
let router_admin = express.Router();
let config = require('../../config');
let common = require('../../libs/common');

// 所有进入admin相关的页面之前，都要校验身份-如果没登录 登录（/admin/login）

router_admin.use((req, res, next) => {
    if (!req.cookies['admin_token'] && req.path != '/login') {
        res.redirect(`/admin/login?ref=${req.path}`); //redirect重定向
    } else {
        if (req.path == '/login') {
            next();
        } else {
            req.db.query(`SELECT * FROM admin_token_table WHERE ID='${req.cookies['admin_token']}'`, (err, data) => {
                if (err) {
                    res.sendStatus(500);
                } else if (data == 0) {
                    res.redirect(`/admin/login?ref=${req.path}`);
                } else {
                    req.admin_ID = data[0]['admin_ID'];
                    next();
                }
            })
        }
    }
})
// 请求login页面
router_admin.get('/login', (req, res) => {
    res.render('login', {
        err_msg: '',
        ref: req.query['ref'] || ''
    });
})



// 请求login接口
router_admin.post('/login', (req, res) => {
    // 管理员分超级管理员和普通管理员  超级管理员和普通管理的数据结构不一样  所以单另出来
    // 超级管理员只存在一个  放数据库的话浪费资源  所以单独放在一个文件夹里进行操作
    let { username,password} = req.body;

    function setToken(id) {
        let ID = common.uuid();
        let oDate = new Date();
        oDate.setMinutes(oDate.getMinutes() + 20);
        let t = Math.floor(oDate.getTime() / 1000);
        req.db.query(`INSERT INTO admin_token_table (ID,admin_ID,expires) VALUES ('${ID}',${id},${t})`, (err, data) => {
            if (err) {
                res.sendStatus(500);
            } else {
                res.cookie('admin_token', ID);
                let ref = req.query['ref'] || '';
                res.redirect(`/admin${ref}`);
            }
        })
    }


    if (username == config.root_user) {
        if (common.md5(password) == config.root_password) {
            console.log('超级管理员已登录');
            setToken(1);
        } else {
            console.log('超级管理员登录失败');
            showError('用户名或密码不正确');
        }
    } else {
        req.db.query(`SELECT * FROM admin_table WHERE username='${username}'`, (err, data) => {
            if (err) {
                showError('数据库出错，请稍后重试');
            } else if (data.length == 0) {
                showError('用户名或密码不正确');
            } else {
                if (data[0].password == common.md5(password)) {
                    console.log('普通管理员已登录');
                    setToken(data[0].ID);
                } else {
                    showError('用户名或密码不正确');
                }
            }
        })
    }

    function showError(msg) {
        res.render(`login`, {
            err_msg: msg,
            ref: req.query['ref'] || ''
        })
    }
})
router_admin.get('/', (req, res) => {
    res.redirect('/admin/house')
})

// 获取数据
router_admin.get('/:table', (req, res) => {
    const {
        table
    } = req.params;
    if (!config[`show_in_admin_${table}`]) {
        res.sendStatus(404);
    } else {
        let aFiled = [];
        let jsonShowName = {};

        config[`show_in_admin_${table}`].split(',').forEach(item => {
            let [field, showName] = item.split(':');

            aFiled.push(field);
            jsonShowName[field] = showName;
        });
        // 分页
        const size = 2;
        let page = req.query['page'];
        if (!page) {
            page = 1;
        } else if (!/^[1-9]\d*$/.test(page)) {
            page = 1;
        }
        let start = (page - 1) * size;
        // 搜索
        // 切空格  
        let like_seg = '1=1';
        if (req.query.keyword) {
            let keys = req.query.keyword.split(/\s+/g);
            like_seg = keys.map(item => `title LIKE '%${item}%'`).join(' OR ');
        }
        // 1.获取数据
        // DESC 降序  ASC 升序
        req.db.query(`SELECT ${aFiled.join(',')} FROM ${table}_table WHERE ${like_seg} ORDER BY create_time DESC LIMIT ${start},${size}`, (err, house_data) => {
            if (err) {
                res.sendStatus(500);
            } else {
                // 2.获取数据总量
                req.db.query(`SELECT COUNT(*) AS c FROM ${table}_table WHERE ${like_seg}`, (err, data) => {
                    if (err) {
                        res.sendStatus(500);
                    } else if (data.length == 0) {
                        res.sendStatus(500);
                    } else {
                        res.render('index', {
                            data: house_data,
                            cur_page: page,
                            show_page_count: 9,
                            all_page_num: Math.ceil(data[0].c / size),
                            keyword: req.query.keyword,
                            jsonShowName,
                            table
                        });
                    }
                })
            }
        })
    }

})
//修改/ 添加
router_admin.post('/:table', (req, res) => {
    let {table} = req.params;

    if (!config[`show_in_admin_${table}`]) {
        res.sendStatus(404);
    } else {
        // req.body['sale_time'] = Math.floor(new Date(req.body['sale_time']).getTime() / 1000);
        // req.body['submit_time'] = Math.floor(new Date(req.body['submit_time']).getTime() / 1000);
        if (req.body['is_mod'] == 'true') {
            let fields = config[`insert_fields_${table}`].split(',');
            config['disallow_modify_fields'].split(',').forEach(name=>{
                fields=fields.filter(item=>item!=name);
            })
            let arr = [];
            fields.forEach(key => {
                arr.push(`${key}='${req.body[key]}'`)
            })

            let sql = `UPDATE ${table}_table SET ${arr.join(',')} WHERE ID='${req.body.old_id}'`;
            req.db.query(sql, (err, data) => {
                if (err) {
                    console.log(err)
                    res.sendStatus(500)
                } else {
                    res.redirect(`/admin/${table}`);
                }
            })
        } else {
            const file_infos={
                'house':{
                    'main_img':{
                        path:'main_img_path',
                        real_path:'main_img_real_path',
                        type:'single'
                    },
                    'img':{
                        path:'img_paths',
                        real_path:'img_real_paths',
                        type:'array'
                    },
                    'property_img':{
                        path:'property_img_paths',
                        real_path:'property_img_real_paths',
                        type:'single'
                    }
                },
                'broker':{
                    'img':{
                        path:'img_path',
                        real_path:'img_real_path',
                        type:'single'
                    }
                },
                'ad':{
                    'img':{
                        path:'img_path',
                        real_path:'img_real_path',
                        type:'single'
                    }

                }
            }
          
            let file_info=file_infos[table]

            const file_paths={};
            const file_real_paths={};


            for(let i = 0; i < req.files.length; i++){
                let name=req.files[i].fieldname
                if(file_info[name]){
                    if(!file_paths[name]){
                        file_paths[name]=[];
                        file_real_paths[name]=[];
                    }
                    file_paths[name].push(req.files[i].filename);
                    file_real_paths[name].push(req.files[i].path.replace(/\\/g, '\\\\'));
                }
            }
            for (let name in file_paths){
                if(file_info[name].type=='single'){
                    req.body[file_info[name].path] = file_paths[name][0];
                    req.body[file_info[name].real_path] = file_real_paths[name][0];
                }else{
                    req.body[file_info[name].path] = file_paths[name].join(',');
                    req.body[file_info[name].real_path] = file_real_paths[name].join(',');
                }
            }




            req.body['ID'] = common.uuid();
            req.body['admin_ID'] = req.admin_ID;


            let arrField = [];
            let arrValue = [];
            
            config[`insert_fields_${table}`].split(',').forEach(item=>{
                arrField.push(item);
                arrValue.push(req.body[item]);
            });
            arrField.push('create_time');
            arrValue.push(Math.floor(new Date().getTime()/1000));
            let sql = `INSERT INTO ${table}_table (${arrField.join(',')}) VALUES ('${arrValue.join("','")}')`;

            req.db.query(sql, err => {
                if (err) {
                    console.log(err)
                    res.sendStatus(500);
                } else {
                    res.redirect(`/admin/${table}`);
                }
            })
        }
    }
})

// 删除
router_admin.use('/:table/delete', require('./delete'));

// 修改
router_admin.get('/:table/get_data', (req, res) => {
    const {table}=req.params;
    const id = req.query.id;
    if (!id) {
        res.sendStatus(404);
    } else if (!/^[\da-f]{32}/.test(id)) {
        res.sendStatus(400);
    } else {
        req.db.query(`SELECT * FROM ${table}_table WHERE ID='${id}'`, (err, data) => {
            if (err) {
                console.log(err)
                res.sendStatus(500);
            } else if (data.length == 0) {
                res.sendStatus(404)
            } else {
                res.send(data[0]);
            }
        })
    }

})
module.exports = router_admin;